package fi.foyt.cs.persistence.dao.items;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import fi.foyt.cs.persistence.dao.GenericDAO;
import fi.foyt.cs.persistence.domainmodel.items.InventoryItem;

public class InventoryItemDAO extends GenericDAO<InventoryItem> {

  public InventoryItem create(Long inventoryId, Long itemId, Integer count) {
    EntityManager entityManager = getEntityManager();

    entityManager.getTransaction().begin();
    try {
      InventoryItem inventoryItem = new InventoryItem();
      inventoryItem.setInventoryId(inventoryId);
      inventoryItem.setItemId(itemId);
      inventoryItem.setCount(count);
      entityManager.persist(inventoryItem);
      entityManager.getTransaction().commit();
      return inventoryItem;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }

  public InventoryItem findByInventoryIdAndItemId(Long inventoryId, Long itemId) {
    EntityManager entityManager = getEntityManager();
    Query query = entityManager.createQuery("select o from InventoryItem o where inventoryId = :inventoryId and itemId = :itemId");
    query.setParameter("inventoryId", inventoryId);
    query.setParameter("itemId", itemId);
    return getSingleResult(query);
  }

  @SuppressWarnings("unchecked")
  public List<InventoryItem> listByInventoryId(Long inventoryId) {
    EntityManager entityManager = getEntityManager();
    Query query = entityManager.createQuery("select o from InventoryItem o where inventoryId = :inventoryId");
    query.setParameter("inventoryId", inventoryId);
    return query.getResultList();
  }

  public InventoryItem updateCount(InventoryItem inventoryItem, Integer count) {
    EntityManager entityManager = getEntityManager();

    entityManager.getTransaction().begin();
    try {
      inventoryItem.setCount(count);
      inventoryItem = entityManager.merge(inventoryItem);
      entityManager.getTransaction().commit();

      return inventoryItem;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }

}
